package com.hanyi.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.DateUtil;
import com.hanyi.common.annotation.Log;
import com.hanyi.common.annotation.RepeatSubmit;
import com.hanyi.common.core.controller.BaseController;
import com.hanyi.common.core.domain.R;
import com.hanyi.common.core.domain.entity.SysDept;
import com.hanyi.common.core.validate.AddGroup;
import com.hanyi.common.enums.BusinessType;
import com.hanyi.common.utils.redis.RedisUtils;
import com.hanyi.system.domain.*;
import com.hanyi.system.service.ISysAnalysisResultService;
import com.hanyi.thirdparty.AlgorithmLicenseResponse;
import com.hanyi.thirdparty.BaseResponse;
import com.hanyi.thirdparty.ServiceVersionResponse;
import com.hanyi.thirdparty.SetGlobalUploadConfigRequest;
import com.hanyi.thirdparty.service.IAlgorithmService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 首页数据统计控制器
 *
 * @author grantfee
 * @date 2023-11-06
 */

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/statistic")
public class SysStatisticController extends BaseController {


    @Autowired
    private ISysAnalysisResultService iSysAnalysisResultService;

    /**
     * 按部门ID获取统计信息
     *
     */
    @SaIgnore
    @GetMapping("/count/{deptId}")
    public R<SysEventStatistic> getStatistic(@PathVariable long deptId) {
        return R.ok(refreshStatistic(deptId));
    }

    /**
     * 按部门ID，分类统计统计数据放入redis缓存
     * **/
    private SysEventStatistic refreshStatistic(long deptId){
        log.info("refresh statics by dept id:"+deptId);
        SysEventStatistic eventStatistic = new SysEventStatistic();
        eventStatistic = new SysEventStatistic();
        SysEventStatistic.TotalCountStatistic totalCountStatistic = new SysEventStatistic.TotalCountStatistic();
        eventStatistic.setTotalCountStatistic(totalCountStatistic);

        DayStatistic dayStatistic = new DayStatistic();
        eventStatistic.setPersonDayStatistic(dayStatistic);
        DayStatistic dayStatistic1 = new DayStatistic();
        eventStatistic.setVehicleDayStatistic(dayStatistic1);
        DayStatistic dayStatistic2 = new DayStatistic();
        eventStatistic.setFaceDayStatistic(dayStatistic2);

        MonthStatistic monthStatistic = new MonthStatistic();
        eventStatistic.setPersonMonthStatistic(monthStatistic);
        MonthStatistic monthStatistic1 = new MonthStatistic();
        eventStatistic.setVehicleMonthStatistic(monthStatistic1);
        MonthStatistic monthStatistic2 = new MonthStatistic();
        eventStatistic.setFaceMonthStatistic(monthStatistic2);

        //统计事件总数
        long totalVehicleEvent = iSysAnalysisResultService.selectCountByVehicle(deptId);
        long totalPersonEvent = iSysAnalysisResultService.selectCountByPerson(deptId);
        long totalFaceEvent = iSysAnalysisResultService.selectCountByFace(deptId);
        log.info("refresh statistic,total person:"+totalPersonEvent+",total vehicle:"+totalVehicleEvent+",total face:"+totalFaceEvent);
        eventStatistic.getTotalCountStatistic().setFaceCount(totalFaceEvent);
        eventStatistic.getTotalCountStatistic().setPersonCount(totalPersonEvent);
        eventStatistic.getTotalCountStatistic().setVeihcleCount(totalVehicleEvent);
        eventStatistic.getTotalCountStatistic().setTotalCount(totalFaceEvent+totalPersonEvent+totalVehicleEvent);


        //////////////////////////统计每小时数据////////////////////////////////////////////
        //按事件类型分类统计，分别是行人，车辆，人脸
        List<Long> personCountList = new ArrayList<>();
        List<Long> vehicleCountList = new ArrayList<>();
        List<Long> faceCountList = new ArrayList<>();

        List<String> hourList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        String startTime = DateUtil.format(cal.getTime(),"yyyy-MM-dd HH:mm:ss");
        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        String endTime = DateUtil.format(cal.getTime(),"yyyy-MM-dd HH:mm:ss");
        log.info("day statistic start time:"+startTime+",endTime:"+endTime);

        List<SysEventHour> eventHours = iSysAnalysisResultService.selectCountByHours(deptId,"0",startTime,endTime);
        List<SysEventHour> eventHours2 = iSysAnalysisResultService.selectCountByHours(deptId,"1",startTime,endTime);
        List<SysEventHour> eventHours3 = iSysAnalysisResultService.selectCountByHours(deptId,"2",startTime,endTime);
        for(int i=0;i<24;i++){
            String hour = String.format("%02d:00",i);
            hourList.add(hour);

            boolean updated=false;
            //统计行人
            if(eventHours != null){
                for(SysEventHour eventHour: eventHours){
                    //log.info("event hour:"+eventHour.getTime()+",count:"+eventHour.getCount());
                    if(eventHour.getTime().equals(hour)){
                        personCountList.add(eventHour.getCount());
                        updated=true;
                    }
                }
            }
            if(!updated){
                personCountList.add(0L);
            }

            //统计车辆
            updated=false;
            if(eventHours2 != null){
                for(SysEventHour eventHour: eventHours2){
                    if(eventHour.getTime().equals(hour)){
                        vehicleCountList.add(eventHour.getCount());
                        updated=true;
                    }
                }
            }
            if(!updated){
                vehicleCountList.add(0L);
            }

            //统计人脸
            updated=false;
            if(eventHours3 != null){
                for(SysEventHour eventHour: eventHours3){
                    if(eventHour.getTime().equals(hour)){
                        faceCountList.add(eventHour.getCount());
                        updated=true;
                    }
                }
            }
            if(!updated){
                faceCountList.add(0L);
            }
        }

        eventStatistic.getPersonDayStatistic().setHours(hourList);
        eventStatistic.getPersonDayStatistic().setCounts(personCountList);
        eventStatistic.getVehicleDayStatistic().setHours(hourList);
        eventStatistic.getVehicleDayStatistic().setCounts(vehicleCountList);
        eventStatistic.getFaceDayStatistic().setHours(hourList);
        eventStatistic.getFaceDayStatistic().setCounts(faceCountList);


        /////////////////统计本月每天数据//////////////////////////////////
        List<String> dayList = new ArrayList<>();
        List<Long> personMonthList = new ArrayList<>();
        List<Long> vehicleMonthList = new ArrayList<>();
        List<Long> faceMonthList = new ArrayList<>();
        Calendar calendar3 = Calendar.getInstance();
        calendar3.set(Calendar.DAY_OF_MONTH, 1);
        calendar3.set(Calendar.HOUR_OF_DAY,0);
        calendar3.set(Calendar.MINUTE,0);
        calendar3.set(Calendar.SECOND,0);
        String startTime2 = DateUtil.format(calendar3.getTime(),"yyyy-MM-dd HH:mm:ss");

        calendar3.add(Calendar.MONTH, 1);
        calendar3.set(Calendar.DAY_OF_MONTH, 1);
        calendar3.add(Calendar.DATE, -1);
        calendar3.set(Calendar.HOUR_OF_DAY,23);
        calendar3.set(Calendar.MINUTE,59);
        calendar3.set(Calendar.SECOND,59);
        String endTime2 = DateUtil.format(calendar3.getTime(),"yyyy-MM-dd HH:mm:ss");

        log.info("month statistic start time:"+startTime2+",end time:"+endTime2);
        List<SysEventDay> eventDays = iSysAnalysisResultService.selectCountByDays(deptId,"0",startTime2,endTime2);
        List<SysEventDay> eventDays1 = iSysAnalysisResultService.selectCountByDays(deptId,"1",startTime2,endTime2);
        List<SysEventDay> eventDays2 = iSysAnalysisResultService.selectCountByDays(deptId,"2",startTime2,endTime2);
        int dayOfMonth = calendar3.get(Calendar.DAY_OF_MONTH);
        for(long i = 1;i <= dayOfMonth;i++){
            String day = String.format("%02d",i);
            dayList.add(day);
            boolean found =false;
            if(eventDays != null){
                for(SysEventDay eventDay: eventDays){
                    //log.info("event day:"+eventDay.getDay()+",count:"+eventDay.getCount());
                    if(eventDay.getDay().equals(day)){
                        found=true;
                        personMonthList.add(eventDay.getCount());
                    }
                }
            }
            if(!found){
                personMonthList.add(0L);
            }

            found =false;
            if(eventDays1 != null){
                for(SysEventDay eventDay: eventDays1){
                    if(eventDay.getDay().equals(day)){
                        found=true;
                        vehicleMonthList.add(eventDay.getCount());
                    }
                }
            }
            if(!found){
                vehicleMonthList.add(0L);
            }

            found =false;
            if(eventDays2 != null){
                for(SysEventDay eventDay: eventDays2){
                    if(eventDay.getDay().equals(day)){
                        found=true;
                        faceMonthList.add(eventDay.getCount());
                    }
                }
            }
            if(!found){
                faceMonthList.add(0L);
            }
        }

        eventStatistic.getPersonMonthStatistic().setDays(dayList);
        eventStatistic.getPersonMonthStatistic().setCounts(personMonthList);
        eventStatistic.getVehicleMonthStatistic().setDays(dayList);
        eventStatistic.getVehicleMonthStatistic().setCounts(vehicleMonthList);
        eventStatistic.getFaceMonthStatistic().setDays(dayList);
        eventStatistic.getFaceMonthStatistic().setCounts(faceMonthList);
        /*personMonthList.forEach(count->{
            System.out.println("person mount:"+count);
        });
        vehicleMonthList.forEach(count->{
            System.out.println("vehicle mount:"+count);
        });
        faceMonthList.forEach(count->{
            System.out.println("face mount:"+count);
        });*/

        return eventStatistic;

    }
}
